#include "pagepath.h"
#include "ui_pagepath.h"
#include "ui_txtdialog.h"
#include <QString>
#include <QPainter>
#include <QImage>
#include <QBoxLayout>
#include <QMessageBox>
#include <QFileDialog>

float map_width = 0;
float map_height = 0;
float map_width_pixel = 0;
float map_height_pixel = 0;
double translate_dx = 0;
double translate_dy = 0;
double translate_dangle = 0;
int toggle_x = 1;
int toggle_y = 1;
QPointF *carpos = new QPointF[1000];
int carpos_cnt = 0;

Bezier *bezier_path = new Bezier[10];
int bezier_num = 1;
int bezier_cnt = 0;


/***************************************************************
  *  @brief     主窗口初始化
  *  @param     parent,继承了QWidget类
  *  @note      无
  *  @Sample usage     无
  *  @author    zh
  *  @      2020/2/17
 **************************************************************/
PagePath::PagePath(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PagePath)
{
    ui->setupUi(this);
    mVesc = 0;

    img = new QImage;
    img->load(":/res/path_image/ground.png");

    translate_dx = ui->Edit_translate_dx->text().toDouble();
    translate_dy = ui->Edit_translate_dy->text().toDouble();
    translate_dangle = ui->Edit_translate_dangle->text().toDouble() - 90;

    map_width_pixel = img->width();
    map_height_pixel = img->height();
    map_width = ui->Edit_map_width->text().toFloat();
    map_height = ui->Edit_map_heigh->text().toFloat();

    bezier_label = new Bezier_Label(ui->imglabel);
    bezier_label->setPixmap( QPixmap::fromImage(*img) );
    bezier_label->resize( img->size() );
    bezier_label->setGeometry(0,0,img->size().width(),img->size().height());

    init_table_out();

    connect(ui->spinBox_kspeed, SIGNAL(valueChanged(int)), ui->Slider_kspeed, SLOT(setValue(int)));
    connect(ui->Slider_kspeed, SIGNAL(valueChanged(int)), ui->spinBox_kspeed, SLOT(setValue(int)));
}

PagePath::~PagePath()
{
    delete ui;
}

void PagePath::init_table_out()
{
    model = new QStandardItemModel;
    QStringList headerList;
    headerList<<"Num"<<"X"<<"Y"<<"Speed"<<"Direct"<<"Angle";
    model->setHorizontalHeaderLabels(headerList);
    ui->table_out->setModel(model);
    ui->table_out->setColumnWidth(0, 50);    //设置列的宽度
    /*ui->table_out->setColumnWidth(1, 50);
    ui->table_out->setColumnWidth(2, 50);
    ui->table_out->setColumnWidth(3, 50);
    ui->table_out->setColumnWidth(4, 50);
    ui->table_out->setColumnWidth(5, 50);*/
}

void PagePath::table_update()
{
    for (int i=0; i <= bezier_path->out_num; i++)
    {
        QString num = QString::asprintf("%d",i);
        aItem = new QStandardItem(num);
        aItem->setTextAlignment(Qt::AlignHCenter);
        model->setItem(i,0,aItem);

        QString x = QString::asprintf("%.3f",bezier_path->out_points[i].X);
        aItem = new QStandardItem(x);
        aItem->setTextAlignment(Qt::AlignHCenter);
        model->setItem(i,1,aItem);

        QString y = QString::asprintf("%.3f",bezier_path->out_points[i].Y);
        aItem = new QStandardItem(y);
        aItem->setTextAlignment(Qt::AlignHCenter);
        model->setItem(i,2,aItem);

        QString speed = QString::asprintf("%d",bezier_path->speed[i]);
        aItem = new QStandardItem(speed);
        aItem->setTextAlignment(Qt::AlignHCenter);
        model->setItem(i,3,aItem);

        QString direct = QString::asprintf("%.3f",bezier_path->direct[i]);
        aItem = new QStandardItem(direct);
        aItem->setTextAlignment(Qt::AlignHCenter);
        model->setItem(i,4,aItem);

        QString angle = QString::asprintf("%.3f",bezier_path->angle[i]);
        aItem = new QStandardItem(angle);
        aItem->setTextAlignment(Qt::AlignHCenter);
        model->setItem(i,5,aItem);
    }
    ui->table_out->setModel(model);
    ui->table_out->verticalHeader()->hide();
}

VescInterface *PagePath::vesc() const
{
    return mVesc;
}

void PagePath::setVesc(VescInterface *vesc)
{
    mVesc = vesc;
    if(mVesc)
    {
        connect(mVesc->commands(), SIGNAL(drawpos(float, float)),
                this, SLOT(drawpos(float, float)));
    }
}

void PagePath::drawpos(float x, float y)
{
    carpos[carpos_cnt++].setX(x);
    carpos[carpos_cnt++].setY(y);
    QString pos_ = "";
    pos_.sprintf("%.3f",x);
    ui->Edit_posx->setText(pos_);
    pos_.sprintf("%.3f",y);
    ui->Edit_posy->setText(pos_);
}

void PagePath::on_Button_bezier_num_clicked()
{
    if( ui->Edit_bezier_num->text().isEmpty() )
    {
        QMessageBox::warning(NULL, "贝塞尔曲线数量不能为0", "请输入正确的数目", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        return;
    }
    bezier_num = ui->Edit_bezier_num->text().toInt();
}

void PagePath::on_Button_load_path_clicked()
{
    translate_dx = ui->Edit_translate_dx->text().toDouble();
    translate_dy = ui->Edit_translate_dy->text().toDouble();
    translate_dangle = ui->Edit_translate_dangle->text().toDouble() - 90;
    if( ui->Edit_x_toggle->text().toInt() )
    {
        toggle_x = ui->Edit_x_toggle->text().toInt();
    }
    if( ui->Edit_x_toggle->text().toInt() )
    {
        toggle_y = ui->Edit_x_toggle->text().toInt();
    }
    bezier_label->update();
}

void PagePath::on_Button_add_bezier_clicked()
{
    bezier_cnt = (bezier_cnt + 1) % bezier_num;
    ui->Edit_bezier_cnt->clear();
    ui->Edit_x0->clear();
    ui->Edit_x1->clear();
    ui->Edit_x2->clear();
    ui->Edit_x3->clear();
    ui->Edit_x4->clear();
    ui->Edit_x5->clear();
    ui->Edit_x6->clear();
    ui->Edit_y0->clear();
    ui->Edit_y1->clear();
    ui->Edit_y2->clear();
    ui->Edit_y3->clear();
    ui->Edit_y4->clear();
    ui->Edit_y5->clear();
    ui->Edit_y6->clear();
    QString cnt = "";
    cnt.sprintf("%d",bezier_cnt);
    ui->Edit_bezier_cnt->setText(cnt);
    QMessageBox::information(NULL, "提示", "请输入过程点",
                             QMessageBox::Yes, QMessageBox::Yes);
}

void PagePath::on_Button_create_path_clicked()
{
    if( ui->Edit_x0->text().isEmpty() )
    {
        QMessageBox::warning(NULL, "过程点数量不能为0", "请输入正确的过程点", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        return;
    }
    bezier_path[bezier_cnt].input_num = 0;
    bezier_path[bezier_cnt].num_btw_two = ui->Edit_num_btw_two->text().toInt();
    bezier_path[bezier_cnt].k_speed = ui->Slider_kspeed->value();
    bezier_path[bezier_cnt].max_speed = ui->Edit_max_speed->text().toInt();
    bezier_path[bezier_cnt].now_angle = ui->Edit_now_angle->text().toFloat();
    bezier_path[bezier_cnt].target_angle = ui->Edit_target_angle->text().toFloat();

    if( !ui->Edit_x0->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[0].X = ui->Edit_x0->text().toFloat();
        bezier_path[bezier_cnt].input_points[0].Y = ui->Edit_y0->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    if( !ui->Edit_x1->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[1].X = ui->Edit_x1->text().toFloat();
        bezier_path[bezier_cnt].input_points[1].Y = ui->Edit_y1->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    if( !ui->Edit_x2->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[2].X = ui->Edit_x2->text().toFloat();
        bezier_path[bezier_cnt].input_points[2].Y = ui->Edit_y2->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    if( !ui->Edit_x3->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[3].X = ui->Edit_x3->text().toFloat();
        bezier_path[bezier_cnt].input_points[3].Y = ui->Edit_y3->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    if( !ui->Edit_x4->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[4].X = ui->Edit_x4->text().toFloat();
        bezier_path[bezier_cnt].input_points[4].Y = ui->Edit_y4->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    if( !ui->Edit_x5->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[5].X = ui->Edit_x5->text().toFloat();
        bezier_path[bezier_cnt].input_points[5].Y = ui->Edit_y5->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    if( !ui->Edit_x6->text().isEmpty() )
    {
        bezier_path[bezier_cnt].input_points[6].X = ui->Edit_x6->text().toFloat();
        bezier_path[bezier_cnt].input_points[6].Y = ui->Edit_y6->text().toFloat();
        bezier_path[bezier_cnt].input_num++;
    }

    bezier_path[bezier_cnt].out_num = (bezier_path[bezier_cnt].input_num - 1) * bezier_path[bezier_cnt].num_btw_two;

    bezier_path[bezier_cnt].ctrlpoints_get();

    bezier_path[bezier_cnt].outpoints_get();

    bezier_path[bezier_cnt].calculate_length();

    bezier_path[bezier_cnt].direct_planning();

    bezier_path[bezier_cnt].angle_planning();

    if(bezier_path[bezier_cnt].input_num == 2)
    {
        bezier_path[bezier_cnt].strghtline_speed_plan();
    }
    else if(bezier_path[bezier_cnt].input_num > 2 && bezier_path[bezier_cnt].input_num < 7)
    {
        bezier_path[bezier_cnt].speed_planning();
    }
    else if (bezier_path[bezier_cnt].input_num == 7)
    {
        bezier_path[bezier_cnt].strghtline_speed_plan();
    }

    /*输入点提醒*/
    ui->plainTextEdit_input->clear();
    QString input_warning = "";
    input_warning.sprintf("第%d条贝塞尔曲线\r\n",bezier_cnt);
    ui->plainTextEdit_input->insertPlainText(input_warning);
    for(int i = 0; i < bezier_path[bezier_cnt].input_num; i++)
    {
        input_warning.sprintf("第%d个点,(%.3f,%.3f)\r\n",i,bezier_path[bezier_cnt].input_points[i].X,bezier_path[bezier_cnt].input_points[i].Y);
        ui->plainTextEdit_input->insertPlainText(input_warning);
    }

    /*输出点个数*/
    ui->Edit_point_num->clear();
    QString bezier_num = "";
    bezier_num.sprintf("%d",bezier_path[bezier_cnt].out_num+1);
    ui->Edit_point_num->setText(bezier_num);

    /*路径长度*/
    ui->Edit_bezier_length->clear();
    QString bezier_length = "";
    bezier_length.sprintf("%.3f",bezier_path[bezier_cnt].length);
    ui->Edit_bezier_length->setText(bezier_length);

    /*输出点提醒*/
    init_table_out();
    table_update();
}

void PagePath::on_Button_create_file_clicked()
{
    if( ui->Edit_file_location->text().isEmpty() )
    {
        QMessageBox::warning(NULL, "无路径", "请输入生成文件路径", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        return;
    }

    /*保存文件*/
    QString address = ui->Edit_file_location->text();
    QFile file(address);
    if(file.open(QFile::WriteOnly|QFile::Truncate| QIODevice::Text | QIODevice::Append))
    {
        char*  ch;
        QString code;
        QByteArray ba = "#include<point.h>\r\n";
        ba.append("/*X    Y   SPEED   DIRECT  ANGLE*/ \r\n");

        for (int i = 0; i < bezier_num; i++)
        {
            code.sprintf("/*No.%d Bezier path has %d points in total.*/",i,bezier_path[i].out_num + 1);
            code.append("\r\n");
            ba.append(code);
            code.sprintf("const Points points_pos[%d]{\r\n",i);
            ba.append(code);
            for(int j = 0; j <= bezier_path[i].out_num; j++)
            {
                code.sprintf("{%f,     %f,     %d,     %f,     %f},",
                             bezier_path[i].out_points[j].X, bezier_path[i].out_points[j].Y,
                             bezier_path[i].speed[j],bezier_path[i].direct[j],bezier_path[i].angle[j]);
                ba.append(code);
                code.sprintf("      /*point ranks %d*/",j);
                code.append("\r\n");
                ba.append(code);
            }
            code.sprintf("};\r\n");
            ba.append(code);
        }

        ch=ba.data();
        file.write(ch);
        file.close();
    }

    /*检验文件是否创建成功*/
    if( !file.open(QFile::ReadOnly) )
    {
        QMessageBox::information(NULL, "warning", "保存文件失败，请检查路径",
                                 QMessageBox::Yes, QMessageBox::Yes);
        return;
    }

    /*通过dialog输出*/
    QString displaystr;
    while (!file.atEnd())
    {
        QByteArray line = file.readLine();
        QString str(line);
        displaystr.append(line);
    }
    QApplication::setOverrideCursor(Qt::WaitCursor);
    txtdialog = new txtDialog(this);
    txtdialog->setModal(false);
    txtdialog->ui->textEdit->setPlainText(displaystr);
    QApplication::restoreOverrideCursor();
    txtdialog->show();
    QMessageBox::information(NULL, "提示", "保存点成功",
                             QMessageBox::Yes, QMessageBox::Yes);
}

void PagePath::on_Button_clear_clicked()
{
    init_table_out();
    ui->plainTextEdit_input->clear();
    ui->Edit_x0->clear();
    ui->Edit_x1->clear();
    ui->Edit_x2->clear();
    ui->Edit_x3->clear();
    ui->Edit_x4->clear();
    ui->Edit_x5->clear();
    ui->Edit_x6->clear();
    ui->Edit_y0->clear();
    ui->Edit_y1->clear();
    ui->Edit_y2->clear();
    ui->Edit_y3->clear();
    ui->Edit_y4->clear();
    ui->Edit_y5->clear();
    ui->Edit_y6->clear();
    ui->Edit_bezier_length->clear();
    ui->Edit_point_num->clear();

    ui->Edit_bezier_cnt->setText("0");
    if(bezier_path)
    {
        delete bezier_path;
        Bezier *bezier_path = new Bezier[10];
    }
    bezier_cnt = 0;
    bezier_num = 1;
}

void PagePath::on_Button_open_folder_clicked()
{
    QString tempDir = QFileDialog::getExistingDirectory(this,
                                                         "Choose directory", "/");
    if( !tempDir.isEmpty() )
    {
        tempDir.append('/');
        QString file_type = ui->File_type->currentText();
        tempDir.append(file_type);
        ui->Edit_file_location->setText(tempDir);
    }
    else
    {
        QMessageBox::information(NULL, "error", "No Directory",
                                 QMessageBox::Yes, QMessageBox::Yes);
        return;
    }

}

void PagePath::on_Button_load_img_clicked()
{
    QString tempFilename = QFileDialog::getOpenFileName(this,
                                                "Choose picture", "/",
                                                "Image Files(*.jpg *.png *.bmp *.jpeg *.gif *.tga)");
    if( !tempFilename.isEmpty() )
    {
        ui->Edit_file_location->setText(tempFilename);
    }
    else
    {
        QMessageBox::information(NULL, "error", "No such file",
                                 QMessageBox::Yes, QMessageBox::Yes);
        return;
    }
    ui->Edit_img_location->setText(tempFilename);
    img->load(tempFilename);

    bezier_label->setPixmap( QPixmap::fromImage(*img) );
    bezier_label->resize( img->size() );
    bezier_label->setGeometry(0,0,img->size().width(),img->size().height());

    map_width_pixel = img->width();
    map_height_pixel = img->height();
    map_width = ui->Edit_map_width->text().toFloat();
    map_height = ui->Edit_map_heigh->text().toFloat();
}

void PagePath::on_Button_cmp_clicked()
{
    mychart = new Mychart;
    mychart->show();
}
